package com.games.fifteenpieces;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MenuActivity extends Activity {
    /** Called when the activity is first created. */
    private Button mBtnLoad, mBtnGame, mBtnExit;
    private TextView mErrorText;
    
    
    
    
    public static final int ACTIVITY_SAVELOAD = 1;
    public static final int ACTIVITY_GAME = 2;
    public static final String KEY_FROM_MENU = "isFromMenu";
    public static final String KEY_GAME_LOADED = "isGameLoaded";
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_activity);
        
       
        
        mBtnLoad = (Button) findViewById(R.id.btnLoad);
        mBtnGame = (Button) findViewById(R.id.btnGame);
        mBtnExit = (Button) findViewById(R.id.btnExit);
        mErrorText = (TextView) findViewById(R.id.errorText);
        mBtnExit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
        
        mBtnLoad.setOnClickListener(new OnClickListener() {
        	
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(ACTIVITY_SAVELOAD);
			}
		});
  
        mBtnGame.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(ACTIVITY_GAME);
			}
		});
        
    }
	
	private void startActivity(int activityId){
		Intent i;
		switch (activityId) {
		case ACTIVITY_GAME:
			i = new Intent(this, GameActivity.class);
			startActivityForResult(i, ACTIVITY_GAME);
			break;
		case ACTIVITY_SAVELOAD:
			i = new Intent(this, SaveLoadActivity.class);
			i.putExtra(KEY_FROM_MENU, true);			
			startActivityForResult(i, ACTIVITY_SAVELOAD);
			break;
		
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case ACTIVITY_GAME:
			if (resultCode == RESULT_CANCELED){
				//ERROR! Crash or something...
				mErrorText.setText("ERROR in GameActivity!");
			}
			if (resultCode == RESULT_OK){
				//Correct finish
				
			}
			if (resultCode == RESULT_FIRST_USER){
				//User does not want to play any more
				finish();
			}
		
			break;
		case ACTIVITY_SAVELOAD:
			if (resultCode == RESULT_OK){
				//
				Intent i = new Intent(this, GameActivity.class);
				i.putExtras(data.getExtras()); //saved game must be in data.extras
				i.putExtra(KEY_GAME_LOADED, true); //telling GameActivity that there is a saved game in extras
				startActivityForResult(i, ACTIVITY_GAME);
			}				
			break;
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

		
}